package com.sfx.concurrent.demo.concurrent.ThreadPoll;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-25
 * Time: 17:59
 */

@Slf4j(topic = "c.MyBlockingQueue")
public class MyBlockingQueue<T> {
    /**
     * 队列存放任务
     */
    private Deque<T> queue = new ArrayDeque<>();

    /**
     * 一把锁,保证线程安全
     */
    private ReentrantLock lock = new ReentrantLock();

    /**
     * 生产者条件变量->满了需要去条件变量等
     */
    private Condition fullCondition = lock.newCondition();

    /**
     * 消费者条件变量
     */
    private Condition emptyCondition = lock.newCondition();

    /**
     * 阻塞队列容量
     */
    private int capacity;

    public MyBlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    /**
     * 阻塞获取任务
     * @return
     */
    public T take() {
        lock.lock();
        try{
            //容量空就去消费者条件变量去等待
            while(queue.isEmpty()) {
                try {
                    emptyCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //当队列中有任务了,就可以从队列头部获取任务,顺便将任务删除掉,有线程执行了
            T t = queue.removeFirst();
            //唤醒生产者可以条件任务了
            fullCondition.signal();
            return t;
        }finally {
            lock.unlock();
        }
    }

    /**
     * 阻塞获取任务,增加超时效果
     * @param timeout
     * @param unit
     * @return
     */
    public T poll(long timeout, TimeUnit unit) {
        lock.lock();
        try{
            //将时间都进行转换为纳秒
            long nanos = unit.toNanos(timeout);
            //容量空就去消费者条件变量去等待
            while(queue.isEmpty()) {
                try {
                    if(nanos<=0) {
                        //超时不等了,返回null
                        return null;
                    }
                    //nanos返回的就是剩余时间
                    nanos = emptyCondition.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            //当队列中有任务了,就可以从队列头部获取任务,顺便将任务删除掉,有线程执行了
            T t = queue.removeFirst();
            //唤醒生产者可以条件任务了
            fullCondition.signal();
            return t;
        }finally {
            lock.unlock();
        }
    }

    /**
     * 阻塞添加任务
     * @param task
     */
    public void put(T task) {
        lock.lock();
        try{
            //队列容量满了阻塞添加
            while(queue.size()==this.capacity) {
                try {
                    log.debug("等待加入到任务队列中{}...",task);
                    fullCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //容量不满就可以向队列中添加任务了
            log.debug("加入到任务队列中{}",task);
            queue.addLast(task);
            //也要唤醒消费者可以执行任务了
            emptyCondition.signal();
        }finally {
            lock.unlock();
        }
    }

    /**
     * 带有超时效果的阻塞添加任务
     * 添加任务成功返回true,否则返回false
     * @param task
     * @param timeout
     * @param unit
     * @return
     */
    public Boolean offer(T task,long timeout,TimeUnit unit) {
        lock.lock();
        try{
            long nanos = unit.toNanos(timeout);
            //队列容量满了阻塞添加
            while(queue.size()==this.capacity) {
                try {
                    if(nanos<=0) {
                        return false;
                    }
                    log.debug("等待加入到任务队列中{}...",task);
                    nanos = fullCondition.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //容量不满就可以向队列中添加任务了
            log.debug("加入到任务队列中{}",task);
            queue.addLast(task);
            //也要唤醒消费者可以执行任务了
            emptyCondition.signal();
            return true;
        }finally {
            lock.unlock();
        }
    }

    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            //判断队列是否已经满了
            if(queue.size()==this.capacity) {
                rejectPolicy.reject(this,task);
            }else {
                log.debug("加入到任务队列中{}",task);
                queue.addLast(task);
                //也要唤醒消费者可以执行任务了
                emptyCondition.signal();
            }
        }finally {
            lock.unlock();
        }
    }
}